package com.shangye.core;

import com.shangye.annotations.RunClass;
import com.shangye.annotations.RunMethod;
import com.shangye.http.HttpServletRequest;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {

    private static Map<String, Method> mapping = new HashMap<>();

    static {
        initMapping();
    }

    private static void initMapping() {
        try {
            File rootDir = new File(HandlerMapping.class.getClassLoader().getResource(".").toURI());

        File dir = new File(rootDir,"com/shangye/controller");
        if (dir.exists()){
            File[] subs = dir.listFiles(f-> f.getName().endsWith(".class"));
            for (File sub : subs){
                String path = sub.getName().replace(".class","");
                Class cls = Class.forName("com.shangye.controller." + path);
                if (cls.isAnnotationPresent(RunClass.class)){

                    Method[] methods = cls.getDeclaredMethods();
                    for (Method method : methods){
                        if (method.isAnnotationPresent(RunMethod.class)){
                            String value = method.getAnnotation(RunMethod.class).value();
                            mapping.put(value,method);
                        }
                    }
                }




            }
        }


        } catch (URISyntaxException | ClassNotFoundException e) {
        e.printStackTrace();
    }
    }

    public static Method getMapping(String key) {
        return mapping.get(key);
    }
}
